<template>
  <x-sub-page class="dict-menu" :content="'字典值管理'" :back="false" @goBack="handleBack">
    <x-filter @search="handleSearch" @reset="handleReset">
      <x-filter-item :label="$t('system.dictValue.dictValueName')">
        <el-input
          v-model="searchParams.dictLabel"
          :placeholder="$t('system.dict.dictNamePlaceholder')"
          maxlength="100"
          clearable
        ></el-input>
      </x-filter-item>
      <x-filter-item :label="$t('system.dict.enable')">
        <x-select
          :placeholder="$t('common.all')"
          v-model="searchParams.state"
          :options="dictOptions['system.state']"
          style="width: 100%"
        ></x-select>
      </x-filter-item>
    </x-filter>
    <!--数据面板-->
    <x-data>
      <!--数据面板按钮插糟-->
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="20">
            <el-button
              type="primary"
              v-hasPermi="['config:dictValue:add']"
              @click="handleAdd"
              :icon="buttonIcons('add')"
            >
              {{ $t('system.dictValue.add') }}</el-button
            >
            <el-button
              type="danger"
              v-hasPermi="['config:dictValue:delete']"
              @click="handleDeleteBatch"
              :icon="buttonIcons('delete')"
            >
              {{ $t('common.batchDelete') }}
            </el-button>
          </el-col>
          <el-col :span="4" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" />
          </el-col>
        </el-row>
      </template>
      <!-- 数据表格 -->
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template slot-scope="scope">
            <!-- <span v-if="item.prop == 'state' || item.prop == 'preset'">{{ changeState(scope.row[item.prop]) }}</span> -->
            <el-switch
              v-if="item.prop === 'state'"
              :value="scope.row[item.prop]"
              active-color="#4474F6"
              inactive-color="#A5A9B2"
              @change="handleChangeState(scope.row[item.prop], scope.row.id)"
              :disabled="!checkBntPermi('config:dictValue:state')"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
            <x-state-cell
              v-else-if="item.prop === 'preset'"
              :stateClass="scope.row[item.prop] === 0 ? 'danger' : 'success'"
              :text="selectDictLabel(dictOptions['system.preset'], scope.row[item.prop])"
            />
            <span v-else-if="item.prop === 'lang'">
              {{ selectDictLabel(dictOptions['system.lang'], scope.row[item.prop]) }}
            </span>
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" :align="'center'" width="160">
          <template slot-scope="scope">
            <more-table-actions
              :permis-list="permissionsActions"
              :action-list="getActions(actions, scope.row)"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
    <!-- 新增 编辑 详情 -->
    <dict-Item-dialog ref="dictItemDialog" :dict-options="dictOptions" @handleSuccess="loadData"></dict-Item-dialog>
  </x-sub-page>
</template>
<script>
  import { selectDictLabel, TableListMixin, QueryDictMixin, PermissionsMixin } from '@package/utils'
  import { mapState } from 'pinia'
  import { buttonIcons } from '@/common/utils/buttonIcon'
  import { pinias } from '@/common/pinia'
  import { columns, actions } from '../config/dictValue.js'
  import {
    apiDeleteDictItemBathDelete,
    listUrl,
    apiPutEnableDictItem,
    apiPutDisableDictItem
  } from '../api/dictValue.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import DictItemDialog from '../components/dictItemDialog.vue'

  const { cachedView } = pinias
  export default {
    name: 'DictValue',
    components: { DictItemDialog },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    inject: ['closePages'],
    data() {
      return {
        columns,
        actions,
        listUrl,
        searchParams: {
          dictLabel: '',
          state: '',
          dictId: this.dictId
        },
        statusOptions: [],
        tableColumns: [],
        selectionData: [],
        tableData: [],
        dictKeys: ['system.state', 'system.preset', 'system.lang'],
        disableMixinCreated: true,
        creatFlag: false
      }
    },
    computed: {
      ...mapState(cachedView, ['visitedViews']),
      dictId() {
        return this.$route.query?.dictId ?? ''
      },
      otherParam() {
        return { dictId: this.dictId }
      },
      getActions() {
        return (actions, row) => {
          const btns = actions.map((action) => {
            if (action.key === 'delete' && row.preset === 1) {
              action.disabled = true
            } else {
              action.disabled = false
            }
            return action
          })
          return btns
        }
      }
    },
    mounted() {
      this.creatFlag = true
      this.handleSearch()
      this.initDictConfig()
    },
    activated() {
      const temp = this.visitedViews.filter((v) => v.path === this.$route.path)
      if (this.disableMixinCreated && this.creatFlag && !temp) {
        this.handleSearch()
      }
    },
    methods: {
      buttonIcons,
      selectDictLabel,
      handleSearch(val) {
        this.queryParam = { ...this.searchParams, ...val }
        this.loadData()
      },
      async handleChangeState(state, id) {
        const { code } = state === 1 ? await apiPutDisableDictItem(id) : await apiPutEnableDictItem(id)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          this.loadData()
        } else {
          this.$message.error(msg)
        }
      },
      /**
       * 重置查询
       *
       */
      handleReset() {
        this.searchParams = {
          dictLabel: '',
          state: '',
          dictId: this.dictId
        }
        this.resetSearch()
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'delete':
            this.$confirm('确定删除该数据, 是否继续?', '提示', {
              confirmButtonText: this.$t('common.sure'),
              cancelButtonText: this.$t('common.cancel')
            })
              .then((confirm) => {
                this.handleDelete([data.id])
              })
              .catch((cancel) => {})
            break
          case 'edit':
            this.$refs.dictItemDialog.handleOpen(data)
            break
          case 'assignMenu':
            this.$router.push('/system/tenant/assignMenu')
            break
          case 'accountTransfer':
            this.$refs.accountTransferDialog.handleOpen(data)
            break
        }
      },
      /**
       * 列表选中数据
       *
       */
      handleSelectionChange(data) {
        this.selectionData = data
      },
      /**
       * 新增
       *
       */
      handleAdd() {
        this.$refs.dictItemDialog.handleOpen({})
      },
      /**
       * 批量删除
       *
       */
      handleDeleteBatch() {
        if (this.selectionData.length === 0) {
          this.$message.error('请选择至少一条数据进行操作')
        } else {
          const ids = this.selectionData
          this.$confirm('确认批量删除吗?', '提示', {
            confirmButtonText: this.$t('common.sure'),
            cancelButtonText: this.$t('common.cancel')
          })
            .then((confirm) => {
              this.handleDelete(ids)
            })
            .catch((cancel) => {})
        }
      },
      /**
       * 删除接口
       *
       */
      handleDelete(infoId) {
        apiDeleteDictItemBathDelete(infoId).then((res) => {
          if (res.code === EnumApiCode.Success) {
            this.$message.success(this.$t('common.deleteSuccess'))
          } else {
            this.$message.error(res.msg)
          }
          this.loadData()
        })
      },
      handleCancel() {
        this.$router.go(-1)
        this.closePages()
      },
      handleSubmit() {},
      handleBack() {
        this.$router.go(-1)
        this.closePages()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .x-sub-page-container.dict-menu {
    // height: auto;
  }

  // .x-sub-page-container .sub-containter {
  //   display: flex;
  //   flex-direction: column;
  // }
</style>
